                                                                                                                                                                                                                                                                 //
//  CMBankRegistCtrl.m
//  CreditManger
//
//  Created by 于会海 on 15/11/10.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CMBankRegistCtrl.h"
#import "CMBankPerfInformatCtrl.h"
#import "UIImageView+WebCache.h"
#import "CMRegistFirstStepInfo.h"
#import "CMRegistFirstStepParam.h"
#import "CMRegistFirstStepParser.h"
#import "CMRegistGetPicCodeUrlInfo.h"
#import "CMRegistGetPicCodeUrlParam.h"
#import "CMRegistGetPicCodeUrlParser.h"
#import "CMBankLoginCtrl.h"
#import "CMLoginManager.h"
#import "CMLoginUserInfo.h"
#import "CheckValid.h"

@interface CMBankRegistCtrl ()<UITextFieldDelegate>
{
    UITextField* nameFiled;
    UITextField* IDCardFiled;
    UITextField* verCodeFiled;
    UIImageView* graphCodeView;
    NSString* timeunit;
    NSString* quantGroupToken;
    NSString* picCodeUrl;
    NSString* toBeString;
    
}
@property (nonatomic, strong)UIButton* reGraphBtn;
@end
@implementation CMBankRegistCtrl
#define Key_NameNumber 7
#define kAlphaNum @"Xx0123456789"
#define kOnlyNum @"0123456789"
#define K_ABC @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmwopqrstuvwxyz"

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)buildLayout{
    self.title = @"央行征信注册";
    [self addNotification];
    [self showDoneWithTitle:@"已有账号"];
    self.view.backgroundColor = [LCCommon getColor:@"F1F5F8"];
    
    UIImage* image = [UIImage imageNamed:@""];
    UIImageView* pageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 40, 40)];
    pageView.image = image;
    pageView.backgroundColor = [LCCommon getColor:@"2999f9"];
    pageView.layer.cornerRadius = 20;
    [self.view addSubview:pageView];
    
    UILabel* topLabel = [self LabelWithRect:CGRectMake(0, 15, 100, 30) textColor:[UIColor blackColor] textstr:@"基本信息" textfont:15 textstyle:NSTextAlignmentCenter];
    topLabel.center = CGPointMake(self.view.centerX, 30);
    [self.view addSubview:topLabel];
    
    UIView* midBackView = [self ViewWithRect:CGRectMake(-1, 60, SCREEN_WIDTH+2, 120) backColor:[UIColor whiteColor]];
    [self.view addSubview:midBackView];
    [self setMidBackViewUI:midBackView];
    
    UIButton* nextBtn = [self buttonWithRect:CGRectMake(10, midBackView.origin.y +120 +15, SCREEN_WIDTH - 20, 40) titleColor:[UIColor whiteColor] titlestr:@"下一步" buttonType:UIButtonTypeSystem];
    nextBtn.backgroundColor = [LCCommon getColor:@"2999f9"];
    [nextBtn addTarget:self action:@selector(nextBtnDone:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
}

- (void)doDone{
    LLog(@"已有账号");
    CMBankLoginCtrl* bankLoginVC = [[CMBankLoginCtrl alloc] init];
    CMNavigationController *nav = [[CMNavigationController alloc]initWithRootViewController:bankLoginVC];
    [UIApplication sharedApplication].keyWindow.rootViewController = nav;
}

- (void)addNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nameFiledChanged:) name:UITextFieldTextDidChangeNotification object:nameFiled];
}

- (void)nameFiledChanged:(NSNotification*) notification{
    if(![nameFiled.text isEqualToString:@""]){
        for (int i=0; i<nameFiled.text.length; i++) {
            NSRange range=NSMakeRange(i,1);
            NSString *subString=[nameFiled.text substringWithRange:range];
            //如果是表情符号，就返回空
            subString = [self disable_emoji:subString];
            if(nameFiled.text.length>20){
                nameFiled.text = @"";
                nameFiled.placeholder = @"请输入您的姓名";
                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"\"姓名\"输入过长,请重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alertView.tag = 3000;
                [alertView show];
                [self.view endEditing:YES];
                return;
            }
        }
    }
}

//禁止输入表情符号
- (NSString *)disable_emoji:(NSString *)text{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString: text
                                                               options: 0
                                                                 range: NSMakeRange(0, [text length])
                                                          withTemplate: @""];
    return modifiedString;
}

- (void)nextBtnDone:(UIButton*)button{
    LLog(@"下一步");

    if ([CheckValid checkStrIsEmpty:nameFiled.text]) {
        [nameFiled becomeFirstResponder];
        DISSMISS_ERRView(@"用户名不能为空",[[[UIApplication sharedApplication] windows] lastObject]);
    }
    if ([CheckValid checkStrIsEmpty:IDCardFiled.text]) {
        [IDCardFiled becomeFirstResponder];
        DISSMISS_ERRView(@"身份证号不能为空",[[[UIApplication sharedApplication] windows] lastObject]);
    }
    if ([CheckValid checkStrIsEmpty:verCodeFiled.text]) {
        [IDCardFiled becomeFirstResponder];
        DISSMISS_ERRView(@"图片验证码不能为空",[[[UIApplication sharedApplication] windows] lastObject]);
    }
    
    NSString *userNameRegex = @"^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]){2,5}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", userNameRegex];
    BOOL isMatch = [pred evaluateWithObject:nameFiled.text];
    if (isMatch == NO) {
        DISSMISS_ERRView(@"请重新输入用户姓名",[[[UIApplication sharedApplication] windows] lastObject]);
        nameFiled.text = @"";
        [nameFiled becomeFirstResponder];
        return;
    }
    if (![CheckValid isValidateIdentityCard:IDCardFiled.text]){
        //DISSMISS_ERR(@"请输入正确的身份号码");
        DISSMISS_ERRView(@"请输入正确的身份号码",[[[UIApplication sharedApplication] windows] lastObject]);
        [IDCardFiled becomeFirstResponder];
        return;
    }
    if (([CheckValid checkStrIsEmpty:nameFiled.text] == YES )|([CheckValid isIncludeEmoji:nameFiled.text])) {
        DISSMISS_ERRView(@"请重新输入用户姓名",[[[UIApplication sharedApplication] windows] lastObject]);
        [nameFiled becomeFirstResponder];
        return;
    }
    [self.view endEditing:YES];
    [self requestToRegister];
}

- (void)requestToRegister{
    CMLoginUserInfo* info = [CMLoginManager getCurrentUserFromUserdefault];
    CMRegistFirstStepParser* parser = [[CMRegistFirstStepParser alloc] init];
    CMRegistFirstStepParam* param = [[CMRegistFirstStepParam alloc] init];
    param.uid = info.uid;
    param.token = info.token;
    param.timeuint = timeunit;
    param.quantGroupToken = quantGroupToken;
    param.realName = nameFiled.text;
    param.cardNo = IDCardFiled.text;
    param.authCode = verCodeFiled.text;
    [NetCenter postDataFromURL:Method_registFirstStep params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            info.cardno = IDCardFiled.text;
            info.username = nameFiled.text;
            [CMLoginManager cacheCurrentUserToUserDefault:info];
            
            CMBankPerfInformatCtrl* perInforVC = [[CMBankPerfInformatCtrl alloc] init];
            perInforVC.quantGroupToken = quantGroupToken;
            perInforVC.timeunit = timeunit;
            [self.navigationController pushViewController:perInforVC animated:YES];
        }else{
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR(error.description);
    }];
}

- (void)setMidBackViewUI:(UIView*)backView{

    UIView* topLine = [self ViewWithRect:CGRectMake(0, 0, SCREEN_WIDTH, 1) backColor:[LCCommon getColor:@"cccccc"]];
    [backView addSubview:topLine];
    UIView* botLine = [self ViewWithRect:CGRectMake(0, backView.size.height-1, SCREEN_WIDTH, 1) backColor:[LCCommon getColor:@"cccccc"]];
    [backView addSubview:botLine];
    
    UIView* secLine = [self ViewWithRect:CGRectMake(10,backView.size.height/3 , SCREEN_WIDTH-10, 1) backColor:[LCCommon getColor:@"cccccc"]];
    [backView addSubview:secLine];
    
    UIView* thirdLine = [self ViewWithRect:CGRectMake(10, secLine.frame.origin.y+40, SCREEN_WIDTH-10, 1) backColor:[LCCommon getColor:@"cccccc"]];
    [backView addSubview:thirdLine];
    
    nameFiled = [self filedWithRect:CGRectMake(10, 0, SCREEN_WIDTH-10, 30) textColor:[LCCommon getColor:@"cccccc"] placeHolder:@"请输入您的真实姓名" textfont:14 textstyle:NSTextAlignmentLeft borderStyle:UITextBorderStyleNone];
    nameFiled.keyboardType = UIKeyboardTypeDefault;
    nameFiled.centerY = 20.0;
    [backView addSubview:nameFiled];
    
    IDCardFiled = [self filedWithRect:CGRectMake(10, secLine.frame.origin.y+10, SCREEN_WIDTH-10, 30) textColor:[LCCommon getColor:@"cccccc"] placeHolder:@"请输入您的身份证号" textfont:14 textstyle:NSTextAlignmentLeft borderStyle:UITextBorderStyleNone];
    IDCardFiled.centerY = 60.0;
    [backView addSubview:IDCardFiled];
    
    verCodeFiled = [self filedWithRect:CGRectMake(10, thirdLine.frame.origin.y+10, SCREEN_WIDTH/2 -10, 30) textColor:[LCCommon getColor:@"cccccc"] placeHolder:@"请输入验证码" textfont:14 textstyle:NSTextAlignmentLeft borderStyle:UITextBorderStyleNone];
    verCodeFiled.centerY = 100.0;
    [backView addSubview:verCodeFiled];
    
    self.reGraphBtn = [self buttonWithRect:CGRectMake(SCREEN_WIDTH - 70, 0, 60, 30) titleColor:[LCCommon getColor:@"cccccc"] titlestr:@"换一张" buttonType:UIButtonTypeSystem];
    self.reGraphBtn.centerY = 100.0;
    [self.reGraphBtn addTarget:self action:@selector(reGetPicCode:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:self.reGraphBtn];
    
    graphCodeView = [self imageViewWithRect:CGRectMake(self.reGraphBtn.frame.origin.x -5-70, 0, 70, 24) placeHolerImage:nil];
    graphCodeView.centerY = 100.0;
    [backView addSubview:graphCodeView];
}

- (UIImageView*)imageViewWithRect:(CGRect)rect placeHolerImage:(UIImage*)image{
    UIImageView* imageView = [[UIImageView alloc] initWithFrame:rect];
    imageView.layer.borderColor = [LCCommon getColor:@"cccccc"].CGColor;
    imageView.layer.borderWidth = 1.0;
    [imageView setImageWithURL:[NSURL URLWithString:@""] placeholderImage:nil options:SDWebImageRefreshCached];
    return imageView;
}

- (UIButton *)buttonWithRect:(CGRect)rect titleColor:(UIColor *)color titlestr:(NSString *)str buttonType:(UIButtonType)btnTyp{
    UIButton* btn = [UIButton buttonWithType:btnTyp];
    btn.frame = rect;
    btn.layer.cornerRadius = 4.0;
    [btn setTitleColor:color forState:UIControlStateNormal];
    [btn setTitle:str forState:UIControlStateNormal];
    return btn;
}

- (UILabel *)LabelWithRect:(CGRect)rect textColor:(UIColor *)color textstr:(NSString *)str textfont:(float)font  textstyle:(NSTextAlignment)aligment{
    UILabel *label = [[UILabel alloc] initWithFrame:rect];
    label.textColor = color;
    label.text = str;
    label.font = [UIFont systemFontOfSize:font];
    label.textAlignment = aligment;
    label.numberOfLines = 0;
    return label;
}

- (UITextField *)filedWithRect:(CGRect)rect textColor:(UIColor *)color placeHolder:(NSString *)placeHolder textfont:(int)font textstyle:(NSTextAlignment)aligment borderStyle:(UITextBorderStyle)sty{
    UITextField *filed = [[UITextField alloc] initWithFrame:rect];
    filed.textColor = color;
    filed.placeholder = placeHolder;
    filed.font = [UIFont systemFontOfSize:font];
    filed.textAlignment = aligment;
    filed.borderStyle = sty;
    filed.delegate = self;
    return filed;
}

- (UIView *)ViewWithRect:(CGRect)rect backColor:(UIColor *)color{
    UIView *view = [[UIView alloc] initWithFrame:rect];
    view.backgroundColor = color;
    return view;
}

- (void)reGetPicCode:(UIButton* )button
{
    [self requestPicCodeUrl];
}

- (void)requestPicCodeUrl{
    CMRegistGetPicCodeUrlParam* param = [[CMRegistGetPicCodeUrlParam alloc] init];
    param.uid = [CMLoginManager getCurrentUserFromUserdefault].uid;
    param.token = [CMLoginManager getCurrentUserFromUserdefault].token;
    CMRegistGetPicCodeUrlParser* parser = [[CMRegistGetPicCodeUrlParser alloc] init];
    
    [NetCenter postDataFromURL:Method_registGetPicCodeUrl params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            CMRegistGetPicCodeUrlInfo* info = (CMRegistGetPicCodeUrlInfo*)myResult.result;
            picCodeUrl = info.url;
            timeunit = info.timeuint;
            quantGroupToken = info.quantGroupToken;
            dispatch_async(dispatch_get_main_queue(), ^{
                [graphCodeView setImageWithURL:[NSURL URLWithString:info.url] placeholderImage:nil options:SDWebImageRefreshCached];
            });
        }else {
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR(error.description);
    }];
}

- (NSString*)getGID{
    NSUUID *identifierForVendor = [[UIDevice currentDevice] identifierForVendor];
    NSString *deviceId = [identifierForVendor UUIDString];
    return deviceId;
}

#pragma mark- textField Delegate
//判断是否是数字，不是的话就输入失败,超过18个字符就会停止
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSCharacterSet *cs;
    if (textField == IDCardFiled) {
        if ([toBeString length]<=17) {
            cs = [[NSCharacterSet characterSetWithCharactersInString:kOnlyNum] invertedSet];
            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
            BOOL canChange = [string isEqualToString:filtered];
            return IDCardFiled.text.length>19?NO: canChange;
        }else if([toBeString length] >17 && [toBeString length]<= 18){
            NSCharacterSet *cs;
            cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
             //按cs分离出数组,数组按@""分离出字符串
            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
            BOOL canChange = [string isEqualToString:filtered];
            return IDCardFiled.text.length>19?NO: canChange;
        }else if ([toBeString length] > 18) {
            return NO;
        }
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 40 - (self.view.frame.size.height - 216.0 -60 -64);
    [UIView animateWithDuration:0.3 animations:^{
        //当textField的frame被键盘覆盖后
        if(offset > 0){
            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
        }
    }];
    if (nameFiled == textField) {
        [UIView animateWithDuration:0.3 animations:^{
            self.view.frame =CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [nameFiled resignFirstResponder];
    [IDCardFiled resignFirstResponder];
    [verCodeFiled resignFirstResponder];
    self.view.frame =CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [self requestPicCodeUrl];
    });
    self.navigationController.navigationBarHidden = NO;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
